package com.sgb.kjwl.view.ui.adapter.shopping;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sgb.kjwl.R;
import com.sgb.kjwl.callback.MyTextWatcher;
import com.sgb.kjwl.model.entity.ShoppingCarEntity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopInfoActivity;
import com.sgb.kjwl.view.widget.RoundImageView;
import com.swgk.core.util.StringUtil;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 购物车的adapter
 * 因为使用的是ExpandableListView，所以继承BaseExpandableListAdapter
 */
public class ShoppingCarAdapter extends BaseExpandableListAdapter {

    private final Context context;
    private final LinearLayout llSelectAll;
    private final ImageView ivSelectAll;
    private final Button btnOrder;
    private final Button btnDelete;
    private final RelativeLayout rlTotalPrice;
    private final TextView tvTotalPrice;
    private List<ShoppingCarEntity> data;
    private boolean isSelectAll = false;
    private double total_price;
    private String goods_image = "";
    private String status = "LIST";
    private boolean isSel;

    public ShoppingCarAdapter(Context context, LinearLayout llSelectAll,
                              ImageView ivSelectAll, Button btnOrder, Button btnDelete,
                              RelativeLayout rlTotalPrice, TextView tvTotalPrice) {
        this.context = context;
        this.llSelectAll = llSelectAll;
        this.ivSelectAll = ivSelectAll;
        this.btnOrder = btnOrder;
        this.btnDelete = btnDelete;
        this.rlTotalPrice = rlTotalPrice;
        this.tvTotalPrice = tvTotalPrice;
    }

    /**
     * 自定义设置数据方法；
     * 通过notifyDataSetChanged()刷新数据，可保持当前位置
     *
     * @param data 需要刷新的数据
     */
    public void setData(List<ShoppingCarEntity> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    @Override
    public int getGroupCount() {
        if (data != null && data.size() > 0) {
            return data.size();
        } else {
            return 0;
        }
    }

    //“LIST”列表模式、“EDITE”编辑模式
    public void setStatus(String status) {
        this.status = status;
        notifyDataSetChanged();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return data.get(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder groupViewHolder;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_shopping_car_group, null);
            groupViewHolder = new GroupViewHolder(convertView);
            convertView.setTag(groupViewHolder);
        } else {
            groupViewHolder = (GroupViewHolder) convertView.getTag();
        }
        final ShoppingCarEntity datasBean = data.get(groupPosition);

        //店铺名称
        String store_name = datasBean.getShopName();

        //店铺内的商品都选中的时候，店铺的也要选中
        for (int i = 0; i < datasBean.getData().size(); i++) {
            ShoppingCarEntity.DataBean goodsBean = datasBean.getData().get(i);
            boolean isSelect = goodsBean.isSelect();
            if (isSelect) {
                datasBean.setSelect_shop(true);
            } else {
                datasBean.setSelect_shop(false);
                break;
            }
        }

        //因为set之后要重新get，所以这一块代码要放到一起执行
        //店铺是否在购物车中被选中
        final boolean isSelect_shop = datasBean.isSelect_shop();
        if (isSelect_shop) {
            groupViewHolder.ivSelect.setImageResource(R.drawable.icon_select_item);
        } else {
            groupViewHolder.ivSelect.setImageResource(R.drawable.icon_no_select_item);
        }

        //店铺选择框的点击事件
        int itemStatus = datasBean.getItemStatus();
        if (itemStatus != 1) {
            if (status.equals("EDITE")) {
                groupViewHolder.ll.setVisibility(View.VISIBLE);
            } else {
                groupViewHolder.ll.setVisibility(View.INVISIBLE);
                groupViewHolder.tvStoreName.setText("失效商品");
                groupViewHolder.tvStoreName.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null);
            }
        } else {
            groupViewHolder.ll.setVisibility(View.VISIBLE);
            groupViewHolder.tvStoreName.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, context.getResources().getDrawable(R.drawable.btn_right_arrow), null);
            if (store_name != null) {
                groupViewHolder.tvStoreName.setText(store_name);
            } else {
                groupViewHolder.tvStoreName.setText("");
            }
            //店铺名称点击
            groupViewHolder.mShopNameLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ShopInfoForCompanyTradesActivity.startAct(context, String.valueOf(datasBean.getShopId()), "", 0, 0);
                }
            });
        }

        groupViewHolder.ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datasBean.setSelect_shop(!isSelect_shop);
                List<ShoppingCarEntity.DataBean> goods = datasBean.getData();
                for (int i = 0; i < goods.size(); i++) {
                    ShoppingCarEntity.DataBean goodsBean = goods.get(i);
                    goodsBean.setSelect(!isSelect_shop);
                }
                notifyDataSetChanged();
            }
        });

        //当所有的选择框都是选中的时候，全选也要选中
        w:
        for (int i = 0; i < data.size(); i++) {
            List<ShoppingCarEntity.DataBean> goods = data.get(i).getData();
            for (int y = 0; y < goods.size(); y++) {
                ShoppingCarEntity.DataBean goodsBean = goods.get(y);
                boolean isSelect = goodsBean.isSelect();
                if (isSelect || goodsBean.getItemStatus() != 1) {
                    isSelectAll = true;
                } else {
                    isSelectAll = false;
                    break w;//根据标记，跳出嵌套循环
                }
            }
        }
        if (isSelectAll) {
            ivSelectAll.setBackgroundResource(R.drawable.icon_select_item);
        } else {
            ivSelectAll.setBackgroundResource(R.drawable.icon_no_select_item);
        }

        //全选的点击事件
        llSelectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSelectAll = !isSelectAll;
                if (isSelectAll) {
                    for (int i = 0; i < data.size(); i++) {
                        List<ShoppingCarEntity.DataBean> goods = data.get(i).getData();
                        for (int y = 0; y < goods.size(); y++) {
                            ShoppingCarEntity.DataBean goodsBean = goods.get(y);
                            goodsBean.setSelect(true);
                        }
                    }
                } else {
                    for (int i = 0; i < data.size(); i++) {
                        List<ShoppingCarEntity.DataBean> goods = data.get(i).getData();
                        for (int y = 0; y < goods.size(); y++) {
                            ShoppingCarEntity.DataBean goodsBean = goods.get(y);
                            goodsBean.setSelect(false);
                        }
                    }
                }
                notifyDataSetChanged();
            }
        });

        //合计的计算
        total_price = 0.00;
        tvTotalPrice.setText("¥0.00");
        for (int i = 0; i < data.size(); i++) {
            List<ShoppingCarEntity.DataBean> goods = data.get(i).getData();
            for (int y = 0; y < goods.size(); y++) {
                ShoppingCarEntity.DataBean goodsBean = goods.get(y);
                boolean isSelect = goodsBean.isSelect();
                //goodsBean.getItemStatus() ==1//过滤失效商品
                if (isSelect && goodsBean.getItemStatus() == 1) {
                    String num = String.valueOf(goodsBean.getItemNum());
                    String price = "0.00";
                    if (goodsBean.getPromoteStatus() == 2) {
                        price = goodsBean.getPromotePrice();
                    } else {
                        price = goodsBean.getPrice();
                    }
                    BigDecimal bNum = new BigDecimal(num);
                    BigDecimal bPrice = new BigDecimal(price);
                    Double money = bNum.multiply(bPrice).doubleValue();
                    BigDecimal bMoney = new BigDecimal(Double.toString(total_price));
                    BigDecimal bMoneys = new BigDecimal(money);
                    total_price = bMoney.add(bMoneys).doubleValue();
                    //让Double类型完整显示，不用科学计数法显示大写字母E
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    tvTotalPrice.setText("¥" + decimalFormat.format(total_price));
                }
            }
        }

        //删除的点击事件
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 通过回调请求后台接口实现删除操作
                 */
                if (mDeleteListener != null) {
                    mDeleteListener.onDelete();
                }
            }
        });

        return convertView;
    }

    public Double getPriceTotal() {
        return total_price;
    }

    static class GroupViewHolder {
        ImageView ivSelect;
        TextView tvStoreName;
        LinearLayout ll;
        LinearLayout mShopNameLl;

        GroupViewHolder(View view) {
            ivSelect = view.findViewById(R.id.iv_select);
            tvStoreName = view.findViewById(R.id.tv_store_name);
            ll = view.findViewById(R.id.ll);
            mShopNameLl = view.findViewById(R.id.shop_name_ll);
        }
    }

    // TODO: 2020/12/7 0007
    // TODO: 2020/12/7 0007
    // TODO: 2020/12/7 0007
    // TODO: 2020/12/7 0007
    // TODO: 2020/12/7 0007
    // TODO: 2020/12/7 0007
    // TODO: 2020/12/7 0007
    // TODO: 2020/12/7 0007
    //------------------------------------------------子布局------------------------------------------------//
    @Override
    public int getChildrenCount(int groupPosition) {
        if (data.get(groupPosition).getData() != null && data.get(groupPosition).getData().size() > 0) {
            return data.get(groupPosition).getData().size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return data.get(groupPosition).getData().get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder childViewHolder;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_shopping_car_child, null);

            childViewHolder = new ChildViewHolder(convertView);
            convertView.setTag(childViewHolder);
        } else {
            childViewHolder = (ChildViewHolder) convertView.getTag();
        }
        final ShoppingCarEntity datasBean = data.get(groupPosition);

        //店铺名称
        String store_name = datasBean.getType();
        //店铺是否在购物车中被选中
        final boolean isSelect_shop = datasBean.isSelect_shop();
        final ShoppingCarEntity.DataBean goodsBean = datasBean.getData().get(childPosition);
        //商品图片
        if (goodsBean.getImageUrls() != null && goodsBean.getImageUrls().size() > 0) {
            goods_image = goodsBean.getImageUrls().get(0);
        }

        //商品ID
        final String goods_id = String.valueOf(goodsBean.getId());
        //商品名称
        String goods_name = goodsBean.getSkuStr();
        //商品价格
        String goods_price = "0.0";
        if (goodsBean.getPromoteStatus() == 2) {
            goods_price = StringUtil.showPrice(goodsBean.getPromotePrice());
            childViewHolder.skuTag.setVisibility(View.VISIBLE);
        } else {
            childViewHolder.skuTag.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(goodsBean.getPrice())) {
                goods_price = StringUtil.showPrice(goodsBean.getPrice());
            }
        }
        //商品数量
        String goods_num = String.valueOf(goodsBean.getItemNum());
        String unit = goodsBean.getUnit();

        //商品是否被选中
        final boolean isSelect = goodsBean.isSelect();

        //tag内容
        String brandName = goodsBean.getBrandName();
        //商品名称
        String cartTitle = goodsBean.getCartTitle();
        //地区
        String areaName = goodsBean.getAreaName();
        String storageName = goodsBean.getStorageName();

        //0 普通商品 ,1 商砼商品
        int cartType = goodsBean.getCartType();
        //是否失效 1未失效
        int itemStatus = goodsBean.getItemStatus();

        Glide.with(context)
                .load(goods_image)
                .into(childViewHolder.ivPhoto);
        if (!TextUtils.isEmpty(goods_name)) {
            childViewHolder.tvName.setVisibility(View.VISIBLE);
            childViewHolder.tvName.setText(goods_name);
        } else {
            childViewHolder.tvName.setVisibility(View.GONE);
        }
        if (goods_price != null) {
            childViewHolder.tvPriceValue.setText(goods_price + "元/" + unit);
        } else {
            childViewHolder.tvPriceValue.setText("");
        }
        if (goods_num != null) {
            childViewHolder.etEditBuyNumber.setText(goods_num);
        } else {
            childViewHolder.etEditBuyNumber.setText("");
        }

        if (cartType == 0) {
            //普通商品
            childViewHolder.tvSt.setVisibility(View.GONE);
        } else if (cartType == 1) {
            //商砼
            childViewHolder.tvSt.setVisibility(View.VISIBLE);
            childViewHolder.tvSt.setText(goodsBean.getConcreteSpec());
        }

        if (itemStatus != 1) {
            //已失效
            childViewHolder.rlAddplus.setVisibility(View.GONE);
            childViewHolder.tvInvalid.setVisibility(View.VISIBLE);
            if (status.equals("LIST")) {
                //结算列表隐藏已失效商品的选择框
                childViewHolder.ivSelect.setVisibility(View.INVISIBLE);
            } else {
                childViewHolder.ivSelect.setVisibility(View.VISIBLE);
            }
        } else {
            childViewHolder.rlAddplus.setVisibility(View.VISIBLE);
            childViewHolder.tvInvalid.setVisibility(View.GONE);
            childViewHolder.ivSelect.setVisibility(View.VISIBLE);
        }

        if (cartTitle != null) {
            childViewHolder.tvProductName.setText(cartTitle);
        } else {
            childViewHolder.tvProductName.setText("");
        }


        //商品是否被选中
        if (isSelect) {
            childViewHolder.ivSelect.setBackgroundResource(R.drawable.icon_select_item);
        } else {
            childViewHolder.ivSelect.setBackgroundResource(R.drawable.icon_no_select_item);
        }

        //商品选择框的点击事件
        childViewHolder.rlChildBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodsBean.setSelect(!isSelect);
                if (!isSelect == false) {
                    datasBean.setSelect_shop(false);
                }
                notifyDataSetChanged();
            }
        });
        // TODO: 2020/12/4 0004
        // TODO: 2020/12/4 0004

        childViewHolder.etEditBuyNumber.setOnFocusChangeListener((v, hasFocus) -> {
            if (isSel){
                if (!hasFocus) {
                    System.out.println("失去焦点");
                    // 失去焦点 输入为空 恢复上次数量
                    if (TextUtils.isEmpty(childViewHolder.etEditBuyNumber.getText().toString())) {
                        childViewHolder.etEditBuyNumber.setText(String.valueOf(goodsBean.getItemNum()));
                    } else {
                        goodsBean.setItemNum(Double.parseDouble(childViewHolder.etEditBuyNumber.getText().toString()));
                        if (mChangeCountListener != null) {
                            mChangeCountListener.onChangeCount(goods_id, goodsBean.getItemNum());
                        }
                    }
                    return;
                }
            }
            isSel = false;
            System.out.println("focus=="+ hasFocus);

        });

        childViewHolder.etEditBuyNumber.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // UiUtil.input(s,  childViewHolder.etEditBuyNumber, 1, "不能低于最低采购量");
            }
        });
        //加号的点击事件
        childViewHolder.ivEditAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //更改本地数据
                double num = goodsBean.getItemNum();
                num++;
                goodsBean.setItemNum(num);

                /**
                 * 实际开发中，通过回调请求后台接口实现数量的加减
                 */
                if (mChangeCountListener != null) {
                    mChangeCountListener.onChangeCount(goods_id, goodsBean.getItemNum());
                }
                notifyDataSetChanged();
            }
        });

        //减号的点击事件
        childViewHolder.ivEditSubtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //更改本地数据
                double num = goodsBean.getItemNum();
                if (num > 1) {
                    num--;
                    goodsBean.setItemNum(num);
                    /**
                     * 实际开发中，通过回调请求后台接口实现数量的加减
                     */
                    if (mChangeCountListener != null) {
                        mChangeCountListener.onChangeCount(goods_id, goodsBean.getItemNum());
                    }
                } else {
                    Toast.makeText(context, "商品不能再减少了", Toast.LENGTH_SHORT).show();
                }
                notifyDataSetChanged();
            }
        });

        childViewHolder.rlItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onClickItemListener != null) {
                    onClickItemListener.onClickItem(goodsBean.getItemId(), goodsBean.getCartType(), goodsBean.getItemStatus(), goodsBean.getSkuid(), String.valueOf(goodsBean.getItemNum()));
                }
            }
        });

        if (childPosition == data.get(groupPosition).getData().size() - 1) {
            //childViewHolder.view.setVisibility(View.GONE);
            childViewHolder.viewLast.setVisibility(View.VISIBLE);
        } else {
            //childViewHolder.view.setVisibility(View.VISIBLE);
            childViewHolder.viewLast.setVisibility(View.GONE);
        }

        return convertView;
    }

    static class ChildViewHolder {
        ImageView ivSelect;
        RelativeLayout rlChildBtn;
        RoundImageView ivPhoto;
        TextView tvName;
        TextView tvProductName;
        TextView tvPriceValue;
        FrameLayout ivEditSubtract;
        // TODO: 2020/12/4 0004
        EditText etEditBuyNumber;
        FrameLayout ivEditAdd;
        ImageView skuTag;
        RelativeLayout rlItem;
        //View view;
        View viewLast;
        TextView tvSt;
        TextView tvInvalid;
        RelativeLayout rlAddplus;

        ChildViewHolder(View views) {
            ivSelect = views.findViewById(R.id.iv_select);
            ivPhoto = views.findViewById(R.id.iv_photo);
            tvName = views.findViewById(R.id.tv_name);
            tvProductName = views.findViewById(R.id.tv_product_name);
            //tvAddress = views.findViewById(R.id.tv_address);
            skuTag = views.findViewById(R.id.sku_tag);
            tvPriceValue = views.findViewById(R.id.tv_price_value);
            ivEditSubtract = views.findViewById(R.id.iv_edit_subtract);
            etEditBuyNumber = views.findViewById(R.id.tv_edit_buy_number);
            ivEditAdd = views.findViewById(R.id.iv_edit_add);
            rlChildBtn = views.findViewById(R.id.rl_child_btn);
            rlItem = views.findViewById(R.id.rl_item);
            tvSt = views.findViewById(R.id.tv_st);
            tvInvalid = views.findViewById(R.id.tv_invalid);
            rlAddplus = views.findViewById(R.id.rl_addplus);

            //view = views.findViewById(R.id.view);
            viewLast = views.findViewById(R.id.view_last);


        }
    }

    //-----------------------------------------------------------------------------------------------//

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    //删除的回调
    public interface OnDeleteListener {
        void onDelete();
    }

    public void setOnDeleteListener(OnDeleteListener listener) {
        mDeleteListener = listener;
    }

    private OnDeleteListener mDeleteListener;

    //修改商品数量的回调
    public interface OnChangeCountListener {
        void onChangeCount(String goods_id, double num);
    }

    public void setOnChangeCountListener(OnChangeCountListener listener) {
        mChangeCountListener = listener;
    }

    private OnChangeCountListener mChangeCountListener;


    //条目点击回调
    public interface OnClickItemListener {
        void onClickItem(String goods_id, int cartType, int itemStatus, String skuId, String orderNo);
    }

    public void setOnClickItemListener(OnClickItemListener listener) {
        onClickItemListener = listener;
    }

    private OnClickItemListener onClickItemListener;
}
